//
//  YPOptionTableViewController.swift
//  YourPassword
//
//  Created by 李冲 on 15/11/25.
//  Copyright © 2015年 Saye. All rights reserved.
//

import UIKit

protocol YPOptionDelegate: class {
    func optionTableViewController(viewController: YPOptionTableViewController,
        completeWithConfig config: YPPasswordConfig)
}

class YPOptionTableViewController: UITableViewController {
    weak var delegate: YPOptionDelegate?
    @IBOutlet weak var numberSwitch: UISwitch!
    @IBOutlet weak var charSwitch: UISwitch!
    @IBOutlet weak var specialSwitch: UISwitch!
    var config: YPPasswordConfig?
    
    static func createEmbedWithNavigation(delegate: YPOptionDelegate, withConfig config: YPPasswordConfig) -> UINavigationController? {
        let storyBoard = UIStoryboard(name: "Options", bundle: NSBundle.mainBundle())
        if let viewController = storyBoard.instantiateInitialViewController() as?
            YPOptionTableViewController
        {
            viewController.config = config
            viewController.delegate = delegate
            let navigationController = UINavigationController(rootViewController: viewController)
            YPGlobal.applyTheme(navigationController)
            return navigationController
        }
        return nil
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        YPGlobal.applyTheme(self)
        self.configSwitch()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "完成", style: .Done, target: self, action: Selector("completeAction:"))
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) {
            if let config = self.config {
                cell.detailTextLabel?.text = String(config.length)
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source


    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
            case 0:
                self.configPasswordLength()
                break;
            default:
                break;
            }
            break
        default:
            break
            
        }
    }
    /*
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    // MARK: - Actions
    func checkSwitch() -> Bool {
        if (self.numberSwitch.on || self.charSwitch.on || self.specialSwitch.on) {
            return true
        }
        else {
            configSwitch()
            let alertController = UIAlertController(title: "错误", message: "不能全关", preferredStyle: .Alert)
            alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            self.presentViewController(alertController, animated: true, completion: nil)
            return false
        }
    }
    func configSwitch() {
        if let passwordSet = self.config?.passwordSet {
            self.numberSwitch.on = passwordSet.contains(YPPasswordSet.Number)
            self.charSwitch.on = passwordSet.contains(YPPasswordSet.Character)
            self.specialSwitch.on = passwordSet.contains(YPPasswordSet.SpecificSymbol)
        }
    }
    func configPasswordLength() {
        let alertController = UIAlertController(title: "密码长度", message: nil, preferredStyle: .Alert)
        alertController.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in
            if let config = self.config {
                textField.text = String(config.length)
            }
        }
        let cancelAction = UIAlertAction(title: "取消", style: .Cancel) { (_) -> Void in
            alertController.dismissViewControllerAnimated(true, completion: nil)
        }
        alertController.addAction(cancelAction)
        let okAction = UIAlertAction(title: "确认", style: .Default) { (_) -> Void in
            alertController.dismissViewControllerAnimated(true, completion: nil)
            let textField = alertController.textFields![0]
            if let text = textField.text {
                if let length = Int(text) {
                    self.config?.length = length
                    if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) {
                        cell.detailTextLabel?.text = text
                    }
                }
            }
        }
        alertController.addAction(okAction)
        
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    
    @IBAction func numberSwitchAction(sender: AnyObject) {
        if !checkSwitch() {
            return
        }
        if (self.numberSwitch.on) {
            self.config?.passwordSet.insert(YPPasswordSet.Number)
        }
        else {
            self.config?.passwordSet.remove(YPPasswordSet.Number)
        }
    }
    @IBAction func charSwitchAction(sender: AnyObject) {
        if !checkSwitch() {
            return
        }
        if (self.charSwitch.on) {
            self.config?.passwordSet.insert(YPPasswordSet.Character)
        }
        else {
            self.config?.passwordSet.remove(YPPasswordSet.Character)
        }
    }
    @IBAction func specialSwitchAction(sender: AnyObject) {
        if !checkSwitch() {
            return
        }
        if (self.specialSwitch.on) {
            self.config?.passwordSet.insert(YPPasswordSet.SpecificSymbol)
        }
        else {
            self.config?.passwordSet.remove(YPPasswordSet.SpecificSymbol)
        }
    }
    func completeAction(sender: AnyObject) {
        self.dismissViewControllerAnimated(true) { () -> Void in
            self.delegate?.optionTableViewController(self, completeWithConfig: self.config!)
        }
    }
}
